{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rX8mhOLljYeM"
      },
      "source": [
        "##### Copyright 2019 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "BZSlp3DAjdYf"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3wF5wszaj97Y"
      },
      "source": [
        "# TensorFlow 2 quickstart for beginners"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DUNzJc4jTj6G"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/quickstart/beginner\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/quickstart/beginner.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/tutorials/quickstart/beginner.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/quickstart/beginner.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "04QgGZc9bF5D"
      },
      "source": [
        "This short introduction uses [Keras](https://www.tensorflow.org/guide/keras/overview) to:\n",
        "\n",
        "1. Build a neural network that classifies images.\n",
        "2. Train this neural network.\n",
        "3. And, finally, evaluate the accuracy of the model."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hiH7AC-NTniF"
      },
      "source": [
        "This is a [Google Colaboratory](https://colab.research.google.com/notebooks/welcome.ipynb) notebook file. Python programs are run directly in the browser—a great way to learn and use TensorFlow. To follow this tutorial, run the notebook in Google Colab by clicking the button at the top of this page.\n",
        "\n",
        "1. In Colab, connect to a Python runtime: At the top-right of the menu bar, select *CONNECT*.\n",
        "2. Run all the notebook code cells: Select *Runtime* > *Run all*."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nnrWf3PCEzXL"
      },
      "source": [
        "Download and install TensorFlow 2. Import TensorFlow into your program:\n",
        "\n",
        "Note: Upgrade `pip` to install the TensorFlow 2 package. See the [install guide](https://www.tensorflow.org/install) for details."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0trJmd6DjqBZ"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7NAbSZiaoJ4z"
      },
      "source": [
        "Load and prepare the [MNIST dataset](http://yann.lecun.com/exdb/mnist/). Convert the samples from integers to floating-point numbers:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7FP5258xjs-v"
      },
      "outputs": [],
      "source": [
        "mnist = tf.keras.datasets.mnist\n",
        "\n",
        "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
        "x_train, x_test = x_train / 255.0, x_test / 255.0"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BPZ68wASog_I"
      },
      "source": [
        "Build the `tf.keras.Sequential` model by stacking layers. Choose an optimizer and loss function for training:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "h3IKyzTCDNGo"
      },
      "outputs": [],
      "source": [
        "model = tf.keras.models.Sequential([\n",
        "  tf.keras.layers.Flatten(input_shape=(28, 28)),\n",
        "  tf.keras.layers.Dense(128, activation='relu'),\n",
        "  tf.keras.layers.Dropout(0.2),\n",
        "  tf.keras.layers.Dense(10)\n",
        "])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l2hiez2eIUz8"
      },
      "source": [
        "For each example the model returns a vector of \"[logits](https://developers.google.com/machine-learning/glossary#logits)\" or \"[log-odds](https://developers.google.com/machine-learning/glossary#log-odds)\" scores, one for each class."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "OeOrNdnkEEcR"
      },
      "outputs": [],
      "source": [
        "predictions = model(x_train[:1]).numpy()\n",
        "predictions"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tgjhDQGcIniO"
      },
      "source": [
        "The `tf.nn.softmax` function converts these logits to \"probabilities\" for each class: "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zWSRnQ0WI5eq"
      },
      "outputs": [],
      "source": [
        "tf.nn.softmax(predictions).numpy()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "he5u_okAYS4a"
      },
      "source": [
        "Note: It is possible to bake this `tf.nn.softmax` in as the activation function for the last layer of the network. While this can make the model output more directly interpretable, this approach is discouraged as it's impossible to\n",
        "provide an exact and numerically stable loss calculation for all models when using a softmax output. "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hQyugpgRIyrA"
      },
      "source": [
        "The `losses.SparseCategoricalCrossentropy` loss takes a vector of logits and a `True` index and returns a scalar loss for each example."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RSkzdv8MD0tT"
      },
      "outputs": [],
      "source": [
        "loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SfR4MsSDU880"
      },
      "source": [
        "This loss is equal to the negative log probability of the true class:\n",
        "It is zero if the model is sure of the correct class.\n",
        "\n",
        "This untrained model gives probabilities close to random (1/10 for each class), so the initial loss should be close to `-tf.math.log(1/10) ~= 2.3`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NJWqEVrrJ7ZB"
      },
      "outputs": [],
      "source": [
        "loss_fn(y_train[:1], predictions).numpy()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9foNKHzTD2Vo"
      },
      "outputs": [],
      "source": [
        "model.compile(optimizer='adam',\n",
        "              loss=loss_fn,\n",
        "              metrics=['accuracy'])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ix4mEL65on-w"
      },
      "source": [
        "The `Model.fit` method adjusts the model parameters to minimize the loss: "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "y7suUbJXVLqP"
      },
      "outputs": [],
      "source": [
        "model.fit(x_train, y_train, epochs=5)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4mDAAPFqVVgn"
      },
      "source": [
        "The `Model.evaluate` method checks the models performance, usually on a \"[Validation-set](https://developers.google.com/machine-learning/glossary#validation-set)\" or \"[Test-set](https://developers.google.com/machine-learning/glossary#test-set)\"."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "F7dTAzgHDUh7"
      },
      "outputs": [],
      "source": [
        "model.evaluate(x_test,  y_test, verbose=2)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "T4JfEh7kvx6m"
      },
      "source": [
        "The image classifier is now trained to ~98% accuracy on this dataset. To learn more, read the [TensorFlow tutorials](https://www.tensorflow.org/tutorials/)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Aj8NrlzlJqDG"
      },
      "source": [
        "If you want your model to return a probability, you can wrap the trained model, and attach the softmax to it:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "rYb6DrEH0GMv"
      },
      "outputs": [],
      "source": [
        "probability_model = tf.keras.Sequential([\n",
        "  model,\n",
        "  tf.keras.layers.Softmax()\n",
        "])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cnqOZtUp1YR_"
      },
      "outputs": [],
      "source": [
        "probability_model(x_test[:5])"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "rX8mhOLljYeM"
      ],
      "name": "beginner.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
